<?php
include_once 'PHP/autoinclude.php';
$database=new Database();
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script>
<script type="text/javascript" src="JavaScript/ArtistList.js"></script>
<script type="text/javascript">
    var result=new ArtistList;
    var limitResults=10;
    var object=new Array();
    
    Event.observe(window, 'load', function() {
       $('searchButton').observe('click',getSongs);
       $('logout').setStyle({display:'none'});
       if(gup('search')){
            new Ajax.Request('Ajax.php',{
               type:'search',
               method:'post',
               parameters:{searchTerm:gup('search')},
               onLoading:loading,
               onSuccess:addSongs
            });
       }
    });

    //****************************************//
    //**Functions concerning user-accounts****//
    //****************************************//
    function logIn(event){
        var userName=$('email').value;
        var pass=$('password').value;
        $('errorLogin').update(createLoader('Logging in'));
        new Ajax.Request('Ajax.php',{
            method:'post',
            parameters:{login:userName,password:pass},
            onSuccess:logged
        });
    }
    function logged(data){
        var response=eval('(' + data.responseText + ')');
        if(response[0]=='error'){
            $('errorLogin').update(nl2br_js(response[1]));
        }
        else{
            $('loginform').setStyle({display:'none'});
            $('logout').setStyle({display:'block'});
            $('reg').setStyle({display:'none'});
            $('username').update(response[1]);
            $('errorLogin').update();
        }
    }
    
    //****************************************//
    //Function to switch the middle***********//
    //****************************************//
    function switchMiddle(arg){
        if(arg=='view'){
            $('middleplay').setStyle({display:'none'});
            $('middleview').setStyle({display:'block'});
            $('wrapperalbums').setStyle({display:'block'});
        }
        else{
            $('middleplay').setStyle({display:'block'});
            $('middleview').setStyle({display:'none'});
            $('wrapperalbums').setStyle({display:'none'});
        }
    }
    
    //****************************************//
    //Functions concerning playing a track****//
    //****************************************//
    function setRating(data){
        var response=data.responseText;
        if(response){
            $$('.current-rating')[0].setStyle({width:response*25+'px'});
        }
    }
    function vote(rating){
        var trackID=$('ytplayer').trackID;
        $$('.current-rating')[0].setStyle({width:rating*25+'px'});
        new Ajax.Request("Ajax.php",{method:"post",parameters:{rate:trackID,rating:rating}});
    }
    
    function playTrack(event){
        switchMiddle('player');
        $('headerplayer').childNodes[1].innerHTML="CURRENTLY PLAYING: "+this.innerHTML;
        var artistName;
        if(this.artistName)
            artistName = this.artistName;
        else
            artistName = result.searchArtist(this.artistID)['name'];
        var trackName = this.objectName;
        $('ytplayer').trackID=this.objectID;
        if($('rating')){
            $('rating').setStyle({display:'none'});
        }
        new Ajax.Request("Ajax.php", {method:"post", parameters:{youtubeGetArtist:artistName,trackName:this.objectName}, onSuccess:updateLink});
        new Ajax.Request("Ajax.php", {method:"post", parameters:{listening:this.objectID,artist:this.artistID}});
        new Ajax.Request("Ajax.php", {method:"post", parameters:{suggestion:this.artistID}, onSuccess:setSuggestions});
        new Ajax.Request("Ajax.php", {method:"post", parameters:{getRating:this.objectID},onSuccess:setRating});
    }
    
    //****************************************//
    //Functions responding to a search query**//
    //****************************************//
    function getSongs(event){
        var searchTerm=$('searchbar').value;
        $('listSuggestions').innerHTML = '';
        new Ajax.Request('Ajax.php',{
           type:'search',
           method:'post',
           parameters:{searchTerm:searchTerm},
           onLoading:loading,
           onSuccess:addSongs
        });
    }
    
    function addSongs(data){
        //remove loading
        var childNodes=$('results').childElements();
        for(var i=0;i<childNodes.length;i++){
            if(childNodes[i].hasClassName('loading')){
                childNodes[i].remove();
            }
        }

        result.list=eval('(' + data.responseText + ')');
        var searchResults=result.searchList();
        console.log(searchResults);
        $('listSongs').innerHTML='';
        for(var a=0;a<searchResults.length;a++){
            if(a==limitResults){
                break;
            }
            var artist = searchResults[a];
            var li=new Element('li');
            var span=new Element('span');
            span.onclick=function(){new Ajax.Request("Ajax.php", {method:"post", parameters:{getArtist:artist['id']}, onSuccess:showArtist});};
            span.update(artist['name']);
            span.objectID=artist['id'];
            span.objectName=artist['name'];
            li.insert(span);
            var ul=new Element('ul');
            for(var t=0;t<artist['search'].length;t++){
                var track = artist['search'][t];
                var liTrack=new Element('li');
                liTrack.artistID=artist['id'];
                liTrack.artistName=artist['name'];
                liTrack.objectID=track['id'];
                liTrack.objectName=track['name'];
                liTrack.onclick=playTrack;
                liTrack.update(track['name']);
                liTrack.setAttribute('class', 'track');
                ul.insert(liTrack);
            }
            li.insert(ul);
            $('listSongs').insert(li);
        }
    }
    
    //****************************************//
    //Functions concerning Suggestions********//
    //****************************************//
    function getSuggestions(event){
        new Ajax.Request('search.php',{
           method:'post',
           parameters:{option:'artist',query:this.innerHTML},
           onSuccess:addSongs
        });
        $('listSuggestions').update();
    }
    
    function setSuggestions(data){
        $('listSuggestions').update();
        var response=eval('('+data.responseText+')');
        for(var i=0; i < 20; i++){                
            var artist = response[i];
            var li=new Element('li');
            var span=new Element('span');
            span.insert(artist['name']);
            span.objectID=artist['id'];
            span.objectName=artist['name'];
            span.observe('click', function(){console.log(this.objectID); new Ajax.Request("Ajax.php", {method:"post", parameters:{getArtist:this.objectID}, onSuccess:showArtist});});
            li.update(span);
            for(var j = 0; j < artist['albums'].length; j++)
            {
                var album = artist['albums'][j];
                var ul = new Element('ul');
                var spanAlbum = new Element('span');
                spanAlbum.insert(album['name']);
                spanAlbum.objectID = album['id'];
                spanAlbum.objectName = album['name'];
                spanAlbum.artistID = artist['id'];
                spanAlbum.artistName = artist['name'];
                ul.update(spanAlbum);
                for(var k = 0; k < album['tracks'].length; k++)
                {
                    var track = album['tracks'][k];
                    var liTrack = new Element('li');
                    liTrack.objectID = track['id'];
                    liTrack.objectName = track['name'];
                    liTrack.albumID = album['id'];
                    liTrack.albumName = album['name'];
                    liTrack.artistID = artist['id'];
                    liTrack.artistName = artist['name'];
                    liTrack.observe("click", playTrack);
                    liTrack.update(track['name']);
                    liTrack.setAttribute('class', 'track');
                    ul.insert(liTrack);
                }
                li.insert(ul);
            }
            $('listSuggestions').insert(li);
        }
    }
    //****************************************//
    // Functions concerning the artist window*//
    //****************************************//
    function showArtist(data){
        var artist;
        if(data.type!="click"){
            artist = eval('('+data.responseText + ')');
            artist = artist[0];
        }
        else{
            artist = result.searchArtist(this.objectID);
        }
        $('bio').update(createLoader('Loading artist info'));
        new Ajax.Request("Ajax.php", {method:"post", parameters:{getArtistInfo:artist['id']},onSuccess:showInfoArtist});
        $('listSongs').update(createLoader('Loading top albums'));
        new Ajax.Request("Ajax.php", {method:"post", parameters:{getArtist:artist['id']}, onSuccess:addAlbums});
        
        $('trackList').update();
        switchMiddle('view');
        var albums=artist['albums'];
        $('albums').update();
        
        var keys=new Array();
        for(var album in albums){
            if(albums.hasOwnProperty(album)){
                keys.push(album)
            }
        }
        for(var i=0;i<keys.length;i++){
            var album=albums[keys[i]];
            var div=new Element('a');
            div.setAttribute('title',album['name']);
            div.setAttribute('class', 'albumcover');
            div.onclick=loadAlbum;
            
            div.objectID=album['id'];
            div.objectName=album['name'];
            div.artistID=artist['id'];
            div.artistName=artist['name'];
            
            var imageAlbum=new Element('img');
            imageAlbum.setAttribute('src',album['cover']);
            div.insert(imageAlbum);
            var albumtitle=new Element('span');
            albumtitle.addClassName('albumtitle');
            albumtitle.insert(shortText(album['name'],30));
            albumtitle.onclick=loadAlbum;
            div.insert(albumtitle);
            $('albums').insert(div);
        }
        //$('listSongs').innerHTML='<li><span>'+artistName['name']+'</span></li>';
    }
    
    function showInfoArtist(data){
        var response=eval('('+data.responseText+')');
        $('bio').update(nl2br_js(response[1]));
        var image=new Element('img');
        image.setAttribute('src',response[0]);
        $('avatar').update();
        $('avatar').insert(image);
    }
    
    function loadArtist(){
        new Ajax.Request("Ajax.php", {method:"post", parameters:{getArtist:this.objectID}, onSuccess:showArtist});
    }
    //****************************************//
    //Functions concerning Albums*************//
    //****************************************//
    function addAlbums(data){
        result.list = eval('('+data.responseText+')');
        var searchResults = result.searchList();
        var artist = searchResults[0];
        
        var li=new Element('li');
        var span=new Element('span');
        span.onclick=showArtist;
        span.update(artist['name']);
        span.objectID=artist['id'];
        li.insert(span);
        console.log(searchResults);
        for(var i = 0; i < 5 && i < artist['albums'].length; i++)
        {
            var album=artist['albums'][i];
            var ul=new Element('ul');
            var spanAlbum = new Element('span');
            spanAlbum.update(album['name']);
            spanAlbum.onclick=loadAlbum;
            spanAlbum.artistID=artist['id'];
            spanAlbum.artistName=artist['name'];
            spanAlbum.objectID=album['id'];
            spanAlbum.objectName=album['name'];
            ul.insert(spanAlbum);
            for(var j = 0; j < 3 && j < album['tracks'].length; j++)
            {
                var liTrack=new Element('li');
                var track=album['tracks'][j];
                var trackID=track['id'];
                liTrack.artistID=artist['id'];
                liTrack.artistName=artist['name'];
                liTrack.albumID=album['id'];
                liTrack.albumName=album['name'];
                liTrack.objectID=track['id'];
                liTrack.objectName=track['name'];
                
                liTrack.onclick=playTrack;
                liTrack.update(track['name']);
                liTrack.setAttribute('class', 'track');
                ul.insert(liTrack);
            }
            li.insert(ul);
        }
        $('listSongs').innerHTML='';
        $('listSongs').insert(li);
        new Ajax.Request("Ajax.php",{method:"post",parameters:{albumInfo:albumName,artistName:artistName},onSuccess:showAlbumInfo});
    }
    
    function loadAlbum(){
        var artistID = this.artistID;
        var albumID = this.objectID;
        $('bio').update(createLoader('Loading album info'));
        new Ajax.Request("Ajax.php",{method:"post",parameters:{albumInfo:albumID,artist:artistID},onSuccess:showAlbumInfo});
        $('trackList').update(createLoader('Loading tracks'));
        new Ajax.Request("Ajax.php", {method:"post", parameters:{getAlbum:albumID},artist:artistID, onSuccess:showAlbum});
    }
    
    function showAlbum(data){
        var album=eval('('+data.responseText+')');
        switchMiddle('view');
        
        var image=new Element('img');
        image.setAttribute('src',album['cover']);

        var h2=new Element('h2');
        h2.innerHTML=album['name'];
        console.log(h2);
        $('headerinfo').update();
        $('headerinfo').insert(h2);
        
        $('avatar').update();
        $('avatar').insert(image);

        $('trackList').update();

        var keys=new Array;
        for(var key in album['tracks']){
            if(album['tracks'].hasOwnProperty(key)){
                keys.push(key);
            }
        }
        var artistID=data.request.options.artist;
        for(var i=0;i<keys.length;i++){
            var track=album['tracks'][keys[i]];
            var li=new Element('li');
            li.setAttribute('class', 'track');
            li.update(track['name']);
            li.onclick=playTrack;
            li.artistID=artistID;
            li.albumID=album['id'];
            li.albumName=album['name'];
            li.objectID=track['id'];
            li.objectName=track['name'];
            $('trackList').insert(li);
        }
    }

    function showAlbumInfo(data){
        var response=data.responseText;
        $('bio').update(nl2br_js(response));
    }
    
    //****************************************//
    //Functions concerning additional functionality
    //****************************************//
    function updateLink(data){
        var link='http://www.youtube.com/embed/'+data.responseText;
        var iframe=new Element('iframe',{'src':link,'width':'550','height':'290'});
        var rating = $('rating');

        $('ytplayer').update();
        $('ytplayer').insert(iframe);
        $('ytplayer').insert(rating);     
        $('rating').setStyle({display:'block'});
    }
    
    function updateSuggestions(data){
        var response=data.responseText;
    }
    
    function createLoader(text){
        var node=new Element('span');
        node.addClassName('loading');
        var textNode=new Element('span');
        textNode.update(text);
        var picNode=new Element('img');
        picNode.setAttribute('src', 'ajax-loader.gif');
        node.insert(textNode);
        node.insert(picNode);
        return node;
    }
    
    function shortText(text,size){
        if(text.length>=size){
            var out=text.substring(0,size);
            out+='...';
            return out;
        }
        return text;
    }
    
    function gup( name )
    {
      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regexS = "[\\?&]"+name+"=([^&#]*)";
      var regex = new RegExp( regexS );
      var results = regex.exec( window.location.href );
      if( results == null )
        return "";
      else
        return results[1];
    }

    function nl2br_js(myString){
        return myString.replace( /\n/g, '<br />\n' );
    }
    
    function loading(data){
        //checks if type is set, for example see addSongs
        if(data['request']['options']['type']){
            //short the path
            var type=data['request']['options']['type'];
            //if the type is search
            if(type=='search'){
                //clear everything
                $('listSongs').update();
                $('trackList').update();
                $('bio').update();
                $('avatar').update();
                $('albums').update();
                $('listSuggestions').update();
                //show loading image
                $('results').insert(createLoader('searching'));
            }
        }
    }
</script>
<title>IKE Music Player</title>
</head>

<body>
    <div id="top"> 
        <div id="whitespace" style="width:40%;float:left;display:block;height:50px;"></div>
            <img src="logo.png" id="logo" />
             <div id="login">

                <span id="reg"><a href="reg.html">Register</a></span><br/>

                <form id="loginform" action="javascript:logIn();" method="post" name="contact_form">
                    <ul>
                        <li>
                            <input  type="text" name="user" placeholder="username" id="email"/>
                        </li>
                        <li>
                            <input type="password" name="pass" placeholder="password" id="password"/>
                        </li>
                        <li>
                            <button id="loginbutton" type="submit" >login</button>
                        </li>
                    </ul>
                </form>


 
                <span id="logout">Welcome <span id='username'></span><br/><a href="logout.php">Log Out</a></span> 
                <span id="errorLogin"></span>
             
        </div>    
    </div>
    
    <div id="blackbar">
       
        <form id="searchForm" action="javascript:getSongs();" method="post" name="contact_form">
              <input type="text" name="user" placeholder="Search for your song or artist" id="searchbar"/>                                  
              <input type="button" id="searchButton" value="Go!"/>             
        </form>        
    </div>
    <div id='loading' style="height:20px;">
    </div>
    <center>
        <div id="main">
            <div id="wrappersug">
                <div id="headersug">
                    <h2>SUGGESTIONS</h2>
                </div>
                <div id="suggestions">
                     <ul id="listSuggestions">
                     </ul>
                </div>
            </div>
            <div id="wrapperres">
                <div id="headerres">
                     <h2>RESULTS</h2>
                </div>
                
                <div id="results">
                    <ul id="listSongs">
                    </ul>
                </div>
            </div>
        
            <div id="middle">
                <div id="middleplay">
                     <div id="wrapperplayer">
                         <div id="headerplayer">
                             <h2>CURRENTLY PLAYING</h2>
                         </div>
                         
                         <div id="ytplayer">

                        <div id="rating">
                         
                         	<div id="ratingInfo">
                         Artist: <span id="artistRatingInfo"></span><br/>
                         Album: <span id="albumRatingInfo"></span>
                         </div>
                             <div id="stars">
                                 <ul class='star-rating'>
                                     <li class='current-rating' id='current-rating'></li>
                                     <li><a href="#" onclick="vote(1); return false;"
                                         title='1 star out of 5' class='one-star'>1</a></li>
                                     <li><a href="#" onclick="vote(2); return false;"
                                         title='2 star out of 5' class='two-stars'>2</a></li>
                                     <li><a href="#" onclick="vote(3); return false;"
                                         title='3 star out of 5' class='three-stars'>3</a></li>
                                     <li><a href="#" onclick="vote(4); return false;"
                                         title='4 star out of 5' class='four-stars'>4</a></li>
                                     <li><a href="#" onclick="vote(5); return false;"
                                         title='5 star out of 5' class='five-stars'>5</a></li>
                                 </ul>
                                 <div id='current-rating-result'></div>
                             </div>
                             
                              <div id="rateit">
                                 <p>Rate It!</p>
                             </div>
                             
                             
                         </div>

                         </div>
                         
                     </div>
                     
                </div>
                
                <div id="middleview">
                    <div id="wrapperartist">
                        <div id="headerinfo">
                            <h2>ARTIST INFO</h2>
                        </div>
        
                        <div id="artistinfo">
                            <div id="avatar">
                            </div>
                            
                            <div id="tracks">
                                <ul id="trackList">
                                </ul>
                            </div>
                            
                            <div id="bio">
                            </div>
                        </div>
                    </div>
                </div>
                
                <div id="wrapperalbums">
                    <div id="headerinfo">
                        <h2>ALBUMS</h2>
                    </div>
        
                    <div id="albums">
                    </div>
                </div>
            </div>
        </div>
    
    </center>
    
    <div id="bottom">
        <span>&copy;2011 VINCENT, POUJA AND PING</span>
    </div>
</body>
</html>